package com.mcm.vistas;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import com.mcm.components.CustomCellEditor;
import com.mcm.components.CustomCellRenderer;
import com.mcm.dto.Producto;
import com.mcm.dto.ProductoVenta;
import com.mcm.modelos.ModeloProducto;

public class VistaProductos extends JPanel implements ActionListener 
{
	private static final long serialVersionUID = 791154312370661343L;
	
	ModeloProducto model;
	JTable table;
	public VistaProductos() 
	{
		setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
		crearGrilla();
	}
	
	private void crearGrilla()
	{
		JPanel panelBusqueda = new JPanel();
		JLabel label = new JLabel("Busqueda", SwingConstants.LEFT);
		final JTextField busqueda = new JTextField();
		busqueda.setPreferredSize(new Dimension(100, 20));
		
		panelBusqueda.add(label);
		panelBusqueda.add(busqueda);
		
		//Grilla productos
		model = new ModeloProducto();
		table = new JTable(model);
		table.setBorder(BorderFactory.createLineBorder(Color.black));
		table.setAutoCreateRowSorter(true);
		
		table.getColumn("C").setCellRenderer(new CustomCellRenderer());
        table.getColumn("C").setMaxWidth(130);
        table.getColumn("C").setCellEditor(new CustomCellEditor(new JCheckBox()));
		
		final Integer[] cols = new Integer[] {0};
		final TableRowSorter<TableModel> sort = (TableRowSorter<TableModel>)table.getRowSorter();
		busqueda.addKeyListener(new KeyAdapter() {
			@Override public void keyReleased(KeyEvent e) {
				String text = busqueda.getText().trim();
				if (text.length() > 0) {
					final List<String> tokens = split(text.toLowerCase());
					sort.setRowFilter(makeRowFilter(tokens, cols));
				} else {
					sort.setRowFilter(null);
				}
			}
		});
		
		getSeparator();
		add(panelBusqueda);
		getScrollPane(table);
		getPanelBotones();
	}
	
	private void getSeparator()
	{
		JSeparator separator = new JSeparator();
		separator.setSize(500, 10);
		separator.setBorder(new EmptyBorder(10, 10, 10, 10));
//		separator.setBorder(BorderFactory.createLineBorder(Color.black));
		add(separator);
	}
	private void getScrollPane(JTable table)
	{
		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setPreferredSize(new Dimension(500, 200));
		add(scrollPane);
	}
	
	public void getPanelBotones()
	{
		JPanel pa = new JPanel();
		
		JButton botonAgregar = new JButton("Agregar");
		botonAgregar.setName("botonAgregar");
		botonAgregar.addActionListener(this);
		
		JButton botonVender = new JButton("Cargar Venta");
		botonVender.setName("botonVenta");
		botonVender.addActionListener(this);
		
		JButton botonGuardar = new JButton("Editar");
		botonGuardar.setName("botonEditar");
		botonGuardar.addActionListener(this);
		
		pa.add(botonAgregar);
		pa.add(botonVender);
		pa.add(botonGuardar);
		
		add(pa);
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if(((JButton)e.getSource()).getName().equals("botonVenta"))
		{
			cargarNuevaVenta();
			
		}else if(((JButton)e.getSource()).getName().equals("botonAgregar"))
		{
			AgregarProducto ap = new AgregarProducto(model);
			ap.setLocationRelativeTo(this);
		}else
		{
			int row = table.getSelectedRow();
			Producto p = model.getElementByRow(row);
			editarProducto(p);
		}
	}
	
	static RowFilter<TableModel,Integer> makeRowFilter(final List<String> tokens, final Integer... cols) 
	{
	    return new RowFilter<TableModel,Integer>() 
	    {
	        @Override public boolean
	        include(Entry<? extends TableModel,? extends Integer> en) 
	        {
	            for (String tok : tokens) 
	            {
	                for (int i = 0; i < cols.length; ++i) 
	                {
	                    String val = en.getStringValue(cols[i]).toLowerCase();
	                    if (val.contains(tok)) 
	                    {
	                        break;
	                    } else if (i == cols.length - 1) 
	                    {
	                        return false;
	                    }
	                }
	            }
	            return true;
	        }
	    };
	}
	
	private void editarProducto(Producto p)
	{
		AgregarProducto ap = new AgregarProducto(model,p);
		ap.setLocationRelativeTo(this);
	}
	
	private static List<String> split(String str) {
        List<String> tokens = new ArrayList<String>();
        StringTokenizer tok = new StringTokenizer(str);
        while (tok.hasMoreTokens()) {
            String token = tok.nextToken().trim();
            if (token.length() > 0) {
                tokens.add(token);
            }
        }
        return tokens;
    }
	
	private void cargarNuevaVenta()
	{
		List<ProductoVenta> listaFactura = new ArrayList<ProductoVenta>();
		int x=0;
		for(Producto p : model.getList())
		{
			if(p.isChequeado())
			{
				x++;
				ProductoVenta pv = crearProductoVenta(p, x);
				listaFactura.add(pv);
			}
		}
		Venta p = new Venta(listaFactura, model);
		p.setLocationRelativeTo(this);
	}
	
	private ProductoVenta crearProductoVenta(Producto p, int index)
	{
		ProductoVenta pv = new ProductoVenta();
		pv.setNroFila(index);
		pv.setDescripcion(p.getDescripcion());
		pv.setPrecioVenta(p.getPrecioVenta());
//		pv.setCantVenta(0);
		pv.setPrecioTotal(0);
		
		return pv;
	}
}
